#!/usr/bin/env python
# -*- coding: utf-8 -*-

import debug
import ConfigParser
import os
import sys
import imp
import inspect

class Controller(object):
	@debug.entry
	def __init__(self, config_path='../../camfw.conf'):
	    if config_path is False :
		    return
		
	    basepath = os.path.dirname( os.path.abspath(__file__))
	    confpath = os.path.normpath(os.path.join(basepath + '/' + config_path))

	    self.__config = {}
	    self.__config['path'] = config_path
	    self.__config['object'] = ConfigParser.SafeConfigParser()
	    self.__config['object'].read(confpath)
		
	    cams = self.__config['object'].get('global', 'camera')
	    camslist = cams.split(',')

	    self.camera = {}
	    for cam in camslist:
		    camObj = self.__get_camera_object(self.__config['object'].get(cam, 'model'))
		    self.camera[cam] = camObj(dict(self.__config['object'].items(cam)))
	
	@debug.entry
	def __get_camera_object(self, model):
            if model is None :
		return None
		
            currentdir = os.path.dirname(os.path.abspath(__file__))
            sys.path.append(currentdir + '/plugins')
	    mfile, mpathname, mdescription = imp.find_module(model)
	    module = imp.load_module(model, mfile, mpathname, mdescription)
	    modclasses = inspect.getmembers(module, inspect.isclass)
	    for modclass in modclasses:
		if modclass[0] == model:
			return modclass[1]

	    return None

        @debug.entry
        def getCameraList(self):
            cameras = []
            for cam in self.camera.keys():
                resp = self.camera[cam].getCamStatus()
                if 'Success' in resp and resp['Success']:
                   cameras.append(cam)

            return cameras

if __name__ == '__main__':
    controller = Controller()

    cameras = controller.getCameraList()
    print cameras

    for value in cameras:
        print value
        print controller.camera[value].getSnapshot()
        print controller.camera[value].getIPAdder()


